package net.ncraft.mc.easyframework.sql.core;

import net.ncraft.mc.easyframework.context.ApplicationContext;
import net.ncraft.mc.easyframework.sql.SqlApplication;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionManager;
import org.reflections.Reflections;

import java.util.HashSet;
import java.util.Set;

public class DefaultSqlApplication implements SqlApplication {


    private final Set<Class<?>> mappers = new HashSet<>();
    private final ApplicationContext context;
    private final Configuration configuration;
    private final SqlSessionManager manager;

    public DefaultSqlApplication(ApplicationContext context, Configuration configuration, SqlSessionManager manager) {
        this.context = context;
        this.configuration = configuration;
        this.manager = manager;
    }

    @Override
    public void scan(Class<?> baseClass) {
        Reflections rf = new Reflections(baseClass);
        Set<Class<?>> mappers = rf.getTypesAnnotatedWith(Mapper.class);
        for (Class<?> mapper : mappers) {
            if (!mapper.isInterface()) continue;
            configuration.addMapper(mapper);
            this.mappers.add(mapper);
        }
    }

    @Override
    public void register() {
        for (Class<?> mapper : mappers) {
            Object bean = manager.getMapper(mapper);
            context.addBean(mapper, bean);
        }
        context.reAutowire();
    }
}
